/**
 * 网络请求工具类
 * 基于uni.request封装，提供类似axios的API体验
 */

import { API_CONFIG, getCurrentEnvConfig } from '../api/config'

// 获取当前环境配置
const envConfig = getCurrentEnvConfig()

// 请求配置
const config = {
  baseURL: envConfig.BASE_URL || API_CONFIG.BASE_URL,
  timeout: API_CONFIG.TIMEOUT,
  header: API_CONFIG.DEFAULT_HEADERS
}

// 请求拦截器
const requestInterceptor = (options) => {
  // 添加token等认证信息
  const token = uni.getStorageSync('token')
  if (token) {
    options.header = {
      ...options.header,
      'Authorization': `Bearer ${token}`
    }
  }
  
  // 显示加载提示
  uni.showLoading({
    title: '加载中...',
    mask: true
  })
  
  console.log('请求发送:', options)
  return options
}

// 响应拦截器
const responseInterceptor = (response, resolve, reject) => {
  // 隐藏加载提示
  uni.hideLoading()
  
  console.log('响应接收:', response)
  
  const { statusCode, data } = response
  
  // HTTP状态码检查
  if (statusCode >= 200 && statusCode < 300) {
    // 业务状态码检查 - 根据API文档，成功状态码是'1000'
    if (data.code === '1000' || data.code === 0 || data.success === true) {
      resolve(data)
    } else {
      // 业务错误
      const errorMsg = data.message || data.msg || '请求失败'
      uni.showToast({
        title: errorMsg,
        icon: 'none'
      })
      reject(new Error(errorMsg))
    }
  } else {
    // HTTP错误
    let errorMsg = '网络请求失败'
    switch (statusCode) {
      case 401:
        errorMsg = '未授权，请重新登录'
        // 可以在这里处理登录过期逻辑
        break
      case 403:
        errorMsg = '拒绝访问'
        break
      case 404:
        errorMsg = '请求地址不存在'
        break
      case 500:
        errorMsg = '服务器内部错误'
        break
      default:
        errorMsg = `请求失败 ${statusCode}`
    }
    
    uni.showToast({
      title: errorMsg,
      icon: 'none'
    })
    reject(new Error(errorMsg))
  }
}

// 错误处理
const errorHandler = (error, reject) => {
  uni.hideLoading()
  console.error('请求错误:', error)
  
  let errorMsg = '网络连接失败'
  if (error.errMsg) {
    if (error.errMsg.includes('timeout')) {
      errorMsg = '请求超时'
    } else if (error.errMsg.includes('fail')) {
      errorMsg = '网络连接失败'
    }
  }
  
  uni.showToast({
    title: errorMsg,
    icon: 'none'
  })
  reject(error)
}

// 基础请求方法
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 合并配置
    const requestOptions = {
      url: config.baseURL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        ...config.header,
        ...options.header
      },
      timeout: options.timeout || config.timeout,
      success: (response) => {
        responseInterceptor(response, resolve, reject)
      },
      fail: (error) => {
        errorHandler(error, reject)
      }
    }
    
    // 请求拦截
    const finalOptions = requestInterceptor(requestOptions)
    
    // 发送请求
    uni.request(finalOptions)
  })
}

// 导出常用方法
export default {
  // GET请求
  get(url, params = {}, options = {}) {
    return request({
      url,
      method: 'GET',
      data: params,
      ...options
    })
  },
  
  // POST请求
  post(url, data = {}, options = {}) {
    return request({
      url,
      method: 'POST',
      data,
      ...options
    })
  },
  
  // PUT请求
  put(url, data = {}, options = {}) {
    return request({
      url,
      method: 'PUT',
      data,
      ...options
    })
  },
  
  // DELETE请求
  delete(url, params = {}, options = {}) {
    return request({
      url,
      method: 'DELETE',
      data: params,
      ...options
    })
  },
  
  // 上传文件
  upload(url, filePath, formData = {}, options = {}) {
    return new Promise((resolve, reject) => {
      const token = uni.getStorageSync('token')
      const header = {
        ...options.header
      }
      
      if (token) {
        header['Authorization'] = `Bearer ${token}`
      }
      
      uni.showLoading({
        title: '上传中...',
        mask: true
      })
      
      uni.uploadFile({
        url: config.baseURL + url,
        filePath,
        name: options.name || 'file',
        formData,
        header,
        success: (response) => {
          uni.hideLoading()
          try {
            const data = JSON.parse(response.data)
            if (data.code === '1000' || data.code === 0 || data.success === true) {
              resolve(data)
            } else {
              const errorMsg = data.message || data.msg || '上传失败'
              uni.showToast({
                title: errorMsg,
                icon: 'none'
              })
              reject(new Error(errorMsg))
            }
          } catch (e) {
            reject(new Error('响应数据解析失败'))
          }
        },
        fail: (error) => {
          uni.hideLoading()
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
          reject(error)
        }
      })
    })
  },
  
  // 设置基础URL
  setBaseURL(url) {
    config.baseURL = url
  },
  
  // 设置默认请求头
  setHeader(header) {
    config.header = {
      ...config.header,
      ...header
    }
  }
}
